<?php

namespace App\Repositories\Eloquent;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Container\Container as App;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Carbon;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Auth, Session, DB, Hash, Config;

class MemberRepository extends Repository
{

    protected $app, $debug;
    /**
     * @param App
     */
    public function __construct(App $app)
    {
        parent::__construct($app);

        //调试开关
        $this->debug = env('SMS_DEBUG');
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Member';
    }

    
    /**
     * [用户登录]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function login($request)
    {        

        if( !$this->debug ){
            if($request->smscode != Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }

        if ( Auth::guard()->attempt([
                'mobile' => $request->mobile, 
                'password' => \App\Models\Member::DEFAULT_PASSWORD,
                'status' => \App\Models\Member::STATUS_NORMAL,
            ])) { 
            return $this->responseSuccess('登录成功', $request, route('index'));          
        }

        return $this->responseFail(500, '登录失败');
    }


    /**
     * 应聘信息登记
     * @param  [type] $uuid    [description]
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function recruit($uuid, $request)
    {
        if( $this->checks($request->mobile) )
            return $this->responseFail(403, '手机号码已注册');

        if( !$this->debug ){
            if($request->smscode != Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }

        $member = $this->show($uuid);

        $request->member = $member;

        return $this->store($request);
    }


    /**
     * 个人名下应聘人员
     * @param  [type] $member [description]
     * @return [type]         [description]
     */
    public function list($member)
    {
        /*return $this->model
            ->where('parent_id', $member->id)
            ->orderBy('date','desc')
            ->get();*/
        return $member->children()
                 ->orderBy('date','desc')
                 ->get();
    }

    /**
     * 团队下的应聘人员
     * @param  [type] $member [description]
     * @return [type]         [description]
     */
    public function others($member)
    {
        return $member->children()
                ->orderBy('date','desc')
                ->get();
        
    }


    /**
     * 查询个人名下用户信息
     * @param  [type] $uuid [description]
     * @return [type]       [description]
     */
    public function mine($member, $uuid)
    {
        $recruit = $this->show($uuid);

        if( !$this->ancestor($member, $recruit) )
            return $this->responseFail(404, '团队信息不正确');

        $recruit->age = Carbon::parse($recruit->birthday)->diffInYears();
        
        return $recruit;
    }


    public function verify($member, $uuid, $request)
    {
        $recruit = $this->show($uuid);

        if( !$this->ancestor($member, $recruit) )
            return $this->responseFail(404, '审核信息不正确');

        $result = $this->update([
            'recruit' => $request->status,
        ], $recruit->id);

        if ( !!$result) {
            return $this->responseSuccess('操作成功', $result);
        }

        return $this->responseFail(500, '操作失败');

    }


    public function renew($member, $request)
    {        
        
        if( $this->checks($request->mobile) )
            return $this->responseFail(403, '手机号码已注册');

        if( !$this->debug ){
            if($request->smscode != Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确');
        }

        $result = $this->update([
            'mobile' => $request->mobile,
        ], $member->id);

        if ( !!$result) {
            return $this->responseSuccess('更改账号成功', $result,route('index'));
        }

        return $this->responseFail(500, '更改账号失败');
    }

    /**
     * 按量统计
     * @return [type] [description]
     */
    public function ranks()
    {
        $query = DB::table('mgt_members AS a')
                ->select(DB::raw(" a.*,COUNT(b.id) AS `count` "))
                ->leftjoin('mgt_members AS b', function ($join) {
                    $join->on('a.id', 'b.parent_id');
                })
                ->groupBy('a.id')
                ->having('count', '>',0)
                ->orderBy('count', 'DESC');
                //->toSql();
                
        return $query->get();
        /*
        SELECT a.*,COUNT(b.id) AS `count`
        FROM mgt_members a LEFT JOIN mgt_members b ON a.id = b.parent_id
        GROUP BY a.id
        HAVING `count` > 0
        ORDER BY `count` DESC
        */
        
        /*$result = $this->model->with('children')->get();
        
        $result->map(function ($item, $key) {
            $item->number = $item->number();
        });

        return $result->sortBy('number');
        */

    }
    

    /**
     * 查询用户信息
     * @param  [type] $uuid [description]
     * @return [type]       [description]
     */
    public function show($uuid)
    {
        $member = $this->findBy('uuid', $uuid);

        if(empty($member)){
            return $this->responseFail(404, '登记信息不正确');
        }

        return $member;
    }


    /**
     * 应聘登记保存
     * @param  [type] $request [description]
     * @return [type]          [description]
     */
    public function store($request)
    {
        $result = $this->create([
            'name' => $request->name,
            'passwd' => Hash::make(\App\Models\Member::DEFAULT_PASSWORD),
            'mobile' => $request->mobile,
            'birthday' => $request->birthday,
            'gendar' => $request->gendar,
            'parent_id' => $request->member->id,
            'depth' => $request->member->depth + 1,
            'type' => \App\Models\Member::TYPE_USER,
            'date' => time(),
            'uuid' => (string)Str::uuid(),
            'recruit' => \App\Models\Member::RECRUIT_NEW,
            'status' => \App\Models\Member::STATUS_NORMAL,
            'avatar' => $request->gendar == 1?mt_rand(1228037,1228058):mt_rand(1228059,1228086),
            'desc' => $request->desc,
        ]);        
       
        if (!!$result)
            return $this->responseSuccess('应聘登记成功', $result, route('success',$result->uuid));
        
        return $this->responseFail(500, '应聘登记失败');
    }


    /**
     * 根据个人信息生成二维码
     * @param  [type] $member [description]
     * @return [type]         [description]
     */
    public function qrcode($member)
    {
        $uuid = $member->uuid;

        if( !$uuid){

            $uuid = (string)Str::uuid();

            $result = $this->update([
                'uuid' => $uuid,
            ], $member->id);

        }

        $file = public_path('qrcodes/'.$uuid.'.png');

        if( !is_file( $file )){

            $logo = public_path('assets/images/logo-qrcode.png');

            $png = base64_encode(
                QrCode::errorCorrection('H')
                ->format('png')
                ->size(300)
                ->merge($logo, .3, true)
                ->generate('http://'.env('WX_DOMAIN').'/m/'.$uuid, public_path('qrcodes/'.$uuid.'.png'))
            );
        }
        
        return $file;
    }


    public function teams($member, $uuid)
    {
        $child = $this->findBy('uuid', $uuid);

        if(empty($child))
            return $this->responseFail(404, '登记信息不正确');

        if( !$this->ancestor($member, $child) )
            return $this->responseFail(404, '团队信息不正确');

        $result = $child->children()->get();

        return $result;
    }


    /**
     * 寻找祖先
     * @param  [type] $member [description]
     * @param  [type] $uuid   [description]
     * @return [type]         [description]
     */
    protected function ancestor($member, $child)
    {
        
        if( $child->depth == 0 )
            return false;
        
        //儿子级
        if( $child->parent->id == $member->id )
            return true;

        //孙子及以下
        $parents = new Collection;

        $this->parents($child, $parents);
        
        foreach( $parents as $parent){
            if($parent->id == $member->id)
                return true;
        }

        return false;

    }

    /**
     * 根据ID遍历父级
     * @param  [type] $child  [description]
     * @param  [type] $result [description]
     * @return [type]         [description]
     */
    private function parents($child, $result)
    {
        if($child->depth !== 0){
            
            $parent = $child->parent;

            $result->push($parent);

            $this->parents($parent, $result);
        }
    }


    protected function checks($mobile)
    {
        return !empty($this->findBy('mobile', $mobile));
    }

}